package com.example.eventbus;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.example.eventbus.databinding.MainLayoutBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    private MainLayoutBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.main_layout);
        binding.zc.setOnClickListener((v -> {
            EventBus.getDefault().register(MainActivity.this);
            Toast.makeText(this, "已注册", Toast.LENGTH_SHORT).show();
        }));
        binding.tz.setOnClickListener((v -> {
            startActivity(new Intent(MainActivity.this,SecondActivity.class));
        }));
        binding.fs.setOnClickListener(v -> {
            EventBus.getDefault().postSticky(new MessageEvent("粘性发送"));
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onMooEvent(MessageEvent messageEvent){
        binding.text.setText(messageEvent.getString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}